<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="角色名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <appSelect v-model="listQuery.appId" placeholder="所属应用"></appSelect>
      <companySelect v-model="listQuery.company" placeholder="所属商户"></companySelect>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
          <div>
            <span class="link-type" style="font-size: 5px;" @click="handleUserRole(row.id)">授于用户</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="编码" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属商户" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属应用" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.appName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="230px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="230px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="success" @click="handleTree(row,$index)">
            分配资源
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="temp.code" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" />
        </el-form-item>
        <el-form-item label="商户" prop="company">
          <companySelect v-model="temp.company" placeholder="所属商户"></companySelect>
        </el-form-item>
        <el-form-item label="应用">
          <app-select v-model="temp.appId" placeholder="所属应用"></app-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="roleTemp.roleTitle" :visible.sync="permsTreeStatus">
      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        show-checkbox
        :check-strictly="strictly"
        class="permission-tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
                <i :class="data.icon"></i>{{ data.description }}&nbsp;
                <span :style="'font-size:8px;'+ (data.type == 0 ? 'color:#1890ff;' : 'color:#42b983;')">[{{ data.type == 0 ? '菜单' : '资源' }}] {{data.url}}</span>
            </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permsTreeStatus = false">
          取消
        </el-button>
        <el-button type="primary" @click="savePermissions()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    roleList,
    roleCreate,
    roleUpdate,
    roleDelete,
    permissionTree,
    permissionRoleUpdate
  } from '@/api/sys'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import appSelect from '@/views/app/components/appSelect' // secondary package based on el-pagination
  import companySelect from '@/views/app/components/companySelect' // secondary package based on el-pagination

  export default {
    name: 'sysRole',
    components: { Pagination, appSelect, companySelect },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'danger',
          1: 'success'
        }
        return statusMap[status]
      },
      sexFilter(status) {
        const statusMap = {
          1: 'error',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      var name = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('模拟后台校验，请输入用户名'));
        } else {
          callback();
        }
      }
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 15,
          name: '',
          company: '',
          sort: '+id'
        },
        temp: {
          id: undefined,
          name: '',
          code: '',
          description: '',
          company: '',
          appId: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          name: [{ validator: name, trigger: 'blur' }],
          code: [{ required: true, pattern:/^[a-z]+$/, message: '请填写角色编码, 规则: 小写字母, 例: admin', trigger: 'blur' }],
          company: [{ required: true, message: '请选择商户', trigger: 'blur' }]
        },
        permsTreeStatus: false,
        strictly: true,
        treeData: [],
        roleTemp: {
          id: undefined,
          perms: [],
          roleTitle: ''
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        roleList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = parseInt(response.data.totalElements)

          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          code: '',
          description: '',
          company: '',
          appId: undefined
        }
      },
      handleCreate() {
        this.resetTemp()

        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })

      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            roleCreate(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {

        this.temp = Object.assign({}, row) // copy obj
        this.temp.status = row.status + "";
        this.temp.gender = row.gender + "";
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })

      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            roleUpdate(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row, index) {
        const tempData = {};
        tempData.id = row.id;
        const that = this;
        this.$confirm('确认删除？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(function(){
          roleDelete(tempData).then(() => {
            that.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            that.getList()
          })
        }).catch(function(){
          // console.log("取消成功！");
        })
      },
      handleUserRole(uId) {
        this.dialogPvVisible = true
        // fetchRole(uId).then(response => {
        //   this.pvData = response.data.pvData
        //   this.dialogPvVisible = true
        // })
      },
      handleTree(row, index) {
        permissionTree({roleId:[row.id]}).then(response => {
          this.treeData = response.data.tree;
          this.roleTemp.id = row.id;
          this.roleTemp.roleTitle = "分配菜单资源-当前角色: [" + row.name + "]";
          this.roleTemp.perms = response.data.perms;
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(response.data.perms)
            for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
              if(this.$refs.tree.store._getAllNodes()[i].level < 2){
                this.$refs.tree.store._getAllNodes()[i].expanded = true
              }
            }
          })
          this.permsTreeStatus = true
        })
      },
      savePermissions(){
        this.roleTemp.perms = this.$refs.tree.getCheckedKeys()
        permissionRoleUpdate(this.roleTemp).then(response => {
          this.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>

<style lang="scss" scoped>

  .user-avatar {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }

</style>
